package com.esun.common.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.util.Objects;

/**
 * 文件工具
 *
 * @author John.xiao
 * @date 2021/3/5 15:40
 */
@Slf4j
public class FileUtils {
	public static InputStream getResourcesFileInputStream(String fileName) {
		return Thread.currentThread().getContextClassLoader().getResourceAsStream("" + fileName);
	}

	public static String getPath() {
		return FileUtils.class.getResource("/").getPath();
	}

	public static File createNewFile(String pathName) {
		File file = new File(getPath() + pathName);
		if (file.exists()) {
			if (file.delete()){
				log.info("删除文件{}",pathName);
			}
		} else {
			if (!file.getParentFile().exists()) {
				if (file.getParentFile().mkdirs()){
					log.info("创建目录{}",pathName);
				}
			}
		}
		return file;
	}

	public static File readFile(String pathName) {
		return new File(getPath() + pathName);
	}

	public static File readUserHomeFile(String pathName) {
		return new File(System.getProperty("user.home") + File.separator + pathName);
	}

	public void downLoad(String path) {
		HttpServletResponse response = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getResponse();
		try {
			//获取项目路径\
			System.out.println(path);
			// path： 欲下载的文件的路径
			File file = new File(path);
			// 获取文件名 - 设置字符集
			String downloadFileName = new String(file.getName().getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
			// 以流的形式下载文件
			InputStream fis;
			fis = new BufferedInputStream(new FileInputStream(path));
			byte[] buffer = new byte[fis.available()];
			int bytes = fis.read(buffer);
			log.info("下载文件大小{} KB", BigDecimal.valueOf(bytes).divide(BigDecimal.valueOf(1024),2,BigDecimal.ROUND_HALF_UP).doubleValue());
			fis.close();
			// 清空response
			assert response != null;
			response.reset();
			// 设置response的Header
			response.addHeader("Content-Disposition", "attachment;filename=" + downloadFileName);
			response.addHeader("Content-Length", "" + file.length());
			OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
			response.setContentType("application/octet-stream");
//			response.setHeader("Access-Control-Allow-Origin", "*");
			toClient.write(buffer);
			toClient.flush();
			toClient.close();
		} catch (IOException ex) {
			ex.printStackTrace();
		}
	}
}
